<?php
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\model\Area;
use app\service\LogService;
use GuzzleHttp\Client;

class SyncAreaData extends Command
{
    protected $apiKey;
    protected $apiUrl = 'https://restapi.amap.com/v3/config/district';
    
    protected function configure()
    {
        $this->setName('sync:area_data')
            ->setDescription('Sync area data from Amap API');
        
        $this->apiKey = env('AMAP_KEY', '');
    }
    
    protected function execute(Input $input, Output $output)
    {
        try {
            if (empty($this->apiKey)) {
                throw new \Exception('请先配置高德地图API KEY');
            }
            
            // 清空现有数据
            Area::where('id', '>', 0)->delete();
            
            // 获取省级数据
            $provinces = $this->getAreaData();
            $count = 0;
            
            foreach ($provinces['districts'][0]['districts'] as $province) {
                // 插入省级数据
                $provinceId = $this->insertArea([
                    'area_name' => $province['name'],
                    'area_code' => $province['adcode'],
                    'parent_id' => 0,
                    'level' => 1
                ]);
                
                $count++;
                
                // 获取市级数据
                $cities = $this->getAreaData($province['adcode']);
                foreach ($cities['districts'][0]['districts'] as $city) {
                    // 插入市级数据
                    $cityId = $this->insertArea([
                        'area_name' => $city['name'],
                        'area_code' => $city['adcode'],
                        'parent_id' => $provinceId,
                        'level' => 2
                    ]);
                    
                    $count++;
                    
                    // 获取区县级数据
                    $districts = $this->getAreaData($city['adcode']);
                    foreach ($districts['districts'][0]['districts'] as $district) {
                        // 插入区县级数据
                        $this->insertArea([
                            'area_name' => $district['name'],
                            'area_code' => $district['adcode'],
                            'parent_id' => $cityId,
                            'level' => 3
                        ]);
                        
                        $count++;
                    }
                }
                
                $output->writeln(sprintf('Synced province: %s', $province['name']));
            }
            
            $output->writeln(sprintf('Successfully synced %d areas', $count));
            
        } catch (\Exception $e) {
            LogService::error('SyncAreaData', sprintf(
                'Sync area data failed: %s',
                $e->getMessage()
            ));
            $output->writeln('<error>' . $e->getMessage() . '</error>');
        }
    }
    
    /**
     * 调用高德API获取区域数据
     */
    protected function getAreaData(string $keywords = ''): array
    {
        $client = new Client();
        
        $response = $client->get($this->apiUrl, [
            'query' => [
                'key' => $this->apiKey,
                'keywords' => $keywords,
                'subdistrict' => 1,
                'extensions' => 'base'
            ]
        ]);
        
        $result = json_decode($response->getBody()->getContents(), true);
        
        if ($result['status'] !== '1') {
            throw new \Exception($result['info']);
        }
        
        return $result;
    }
    
    /**
     * 插入区域数据
     */
    protected function insertArea(array $data): int
    {
        $area = Area::create([
            'area_name' => $data['area_name'],
            'area_code' => $data['area_code'],
            'parent_id' => $data['parent_id'],
            'level' => $data['level'],
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ]);
        
        return $area->id;
    }
} 